<?php
require_once('db_fns.php');
//注册
function register($sno, $passwd, $tel)
{
    $conn = db_connect();
    $result = $conn->query("select * from user where sno='" . $sno . "'");
    if (!$result) {
        throw new Exception("无法执行查询", 1);
    }
    if ($result->num_rows > 0) {
        throw new Exception("该用户已经存在", 1);
        echo '<a href="login.php">点击以返回登录界面</a>';
    }
    $result = $conn->query("insert into user(sno,psw,tel) value ('" . $sno . "',md5('" . $passwd . "'),'" . $tel . "')");
    if (!$result) {
        throw new Exception("注册失败");
    }
    return true;
}
//登录
function login($sno, $passwd)
{
    $conn = db_connect();
    $results = $conn->query("select * from user where sno = '" . $sno . "' and psw = md5('" . $passwd . "')");

    if (!$results) {
        throw new Exception('无法登录');
    }
    if ($results->num_rows > 0) {
        $_SESSION['uid'] = $results->fetch_array()['uid'];
        return true;
    } else {
        throw new Exception('无法登录');
    }
    if (!isset($_SESSION['flag'])) {
        $_SESSION['flag'] = 0;
    }
}
//检查用户是否登录
function check_valid_user()
{
    return isset($_SESSION['valid_user']);
}
//修改用户信息
function change_personal_information($user_logo_name, $user_sex, $user_age, $tel, $user_qq, $user_email)
{
    $conn = db_connect();
    $result = $conn->query("update user set img='" . $user_logo_name . "',sex='" . $user_sex . "',birthday='" . $user_age . "',tel='" . $tel . "',qq='" . $user_qq . "',email='" . $user_email . "' where sno='" . $_SESSION['valid_user'] . "'");
    if (!$result) {
        throw new Exception('修改个人信息失败');
    } else {
        return true;
    }
}
//获取用户信息
function get_user_information($sno)
{
    $conn = db_connect();
    $result = $conn->query("select * from user where sno='" . $sno . "'");
    if (!$result) {
        throw new Exception('获取用户信息失败');
    } else {
        return $result;
    }
}
